﻿// ********************* Vendor *******************************
var Vendor = function(control) {
	var self = this;
	this.control = control;
	this.vendors = [];
	this.selected = 0;
};

Vendor.prototype.Has = function(name) {
	for (var i in this.vendors) {
		if (this.vendors[i].name == name) return true;
	}
	return false;
};

Vendor.prototype.SelectedName = function() {
	return this.control.next().val();
};

Vendor.prototype.SelectedValue = function() {
	for (var i in this.vendors) {
		if (this.vendors[i].name == this.SelectedName()) return this.vendors[i].id;
	}
	return 0;
};

Vendor.prototype.AddValue = function(callback) {
	var self = this;
	$.getJSON('/vendor.aspx', {mode: 'add', name: self.SelectedName(), color: ''}, function(data) {
		var item = {name: self.SelectedName(), id: data.id};
		self.vendors.unshift(item);
		self.control.append('<option value="' + item.id + '">' + item.name + '</option>');
		if (callback) callback();
	});
};

Vendor.prototype.Load = function(selected) {
	var self = this;
	if (selected) self.selected = selected;
	$.getJSON('/vendor.aspx', function (data) {
		self.vendors = data;
		self.control.combobox('destroy').empty();
		self.control.append('<option value="0">--</option>');
		$.each(data, function (index, item) {
			self.control.append('<option value="' + item.id + '">' + item.name + '</option>');
		});
		self.control.combobox({strict: false});
		self.Select(self.selected);
	});
};

Vendor.prototype.Select = function(value) {
	var self = this;
	self.selected = value;
	if (self.vendors.length > 0) {
		if (!value) {
			self.control.val(0);
			self.control.next().val('--');
		} else if (isNaN(parseInt(value))) {
			for (var i in self.vendors) {
				var item = self.vendors[i];
				if (item.name == value) {
					self.control.val(item.id);
					self.control.next().val(item.name);
					break;
				}
			}
		} else {
			for (var i in self.vendors) {
				var item = self.vendors[i];
				if (item.id == value) {
					self.control.val(item.id);
					self.control.next().val(item.name);
					break;
				}
			}
		}
	}
};
